<template>
  <div class="anypay-apple-list-page">
    <div class="anypay-apple-page-header">
      <h1>Protocol3 协议管理</h1>
      <p>
        基于Protocol3系统管理协议配置，支持商户渠道配置和二维码配置协议，以及协议绑定功能
      </p>
    </div>

    <!-- 搜索区域 -->
    <div class="anypay-apple-card anypay-apple-mb-6">
      <a-card>
        <div class="search-container standard">
          <!-- 协议类型 -->
          <div class="search-field">
            <label class="search-label">协议类型:</label>
            <a-select
              v-model:value="searchForm.protocolType"
              placeholder="请选择协议类型"
              class="search-select"
              allowClear
            >
              <a-select-option value="MERCHANT_CHANNEL_CONFIG_V3">商户渠道配置</a-select-option>
              <a-select-option value="QR_CODE_CONFIG">二维码配置</a-select-option>
              <a-select-option value="DEFAULT_PROTOCOL">默认协议</a-select-option>
              <a-select-option value="CHANNEL_ONBOARDING">渠道进件协议</a-select-option>
            </a-select>
          </div>

          <!-- 状态 -->
          <div class="search-field">
            <label class="search-label">状态:</label>
            <a-select
              v-model:value="searchForm.enabled"
              placeholder="请选择状态"
              class="search-select"
              allowClear
            >
              <a-select-option :value="true">启用</a-select-option>
              <a-select-option :value="false">禁用</a-select-option>
            </a-select>
          </div>

          <!-- 渠道 -->
          <div class="search-field">
            <label class="search-label">渠道:</label>
            <a-select
              v-model:value="searchForm.channelCode"
              placeholder="请选择渠道"
              class="search-select"
              allowClear
            >
              <a-select-option 
                v-for="channel in paymentChannels" 
                :key="channel.channelCode" 
                :value="channel.channelCode"
              >
                <div style="display: flex; align-items: center; gap: 8px;">
                  <img 
                    :src="channel.iconUrl" 
                    :alt="channel.channelName" 
                    style="width: 16px; height: 16px; object-fit: contain;" 
                  />
                  <span>{{ channel.channelName }}</span>
                </div>
              </a-select-option>
              <a-select-option value="DEFAULT">
                <div style="display: flex; align-items: center; gap: 8px;">
                  <span style="width: 16px; height: 16px; display: inline-block; text-align: center; color: #ccc;">-</span>
                  <span>默认</span>
                </div>
              </a-select-option>
              <a-select-option value="">
                <div style="display: flex; align-items: center; gap: 8px;">
                  <span style="width: 16px; height: 16px; display: inline-block; text-align: center; color: #ccc;">-</span>
                  <span>无</span>
                </div>
              </a-select-option>
            </a-select>
          </div>

          <!-- 搜索按钮 -->
          <div class="search-actions">
            <a-space>
              <a-button type="primary" @click="handleSearch">
                <SearchOutlined />
                搜索
              </a-button>
              <a-button @click="handleReset">
                <ReloadOutlined />
                重置
              </a-button>
            </a-space>
          </div>
        </div>
      </a-card>
    </div>

    <!-- 数据表格区域 -->
    <div class="anypay-apple-card">
      <a-card>
        <div class="anypay-apple-table anypay-apple-toolbar">
          <AnyTable
            ref="protocolTable"
            :autoLoad="true"
            :dataLoader="loadProtocolData"
            :tableColumns="tableColumns"
            :searchParams="searchParams"
            :tableScroll="{ x: 'max-content' }"
            tableRowKey="protocolId"
            @loadComplete="handleLoadComplete"
          >
            <template #tableToolbar>
              <a-space :size="12">
                <a-button type="primary" @click="handleCreate">
                  <PlusOutlined /> 新增协议
                </a-button>
                <a-button @click="handleTestAll">
                  <ExperimentOutlined /> 批量测试
                </a-button>
                <a-button @click="handleClearCache">
                  <DeleteOutlined /> 清理缓存
                </a-button>
                <a-button @click="handleTestProtocolLookup">
                  <SearchOutlined /> 测试协议查找
                </a-button>
              </a-space>
            </template>
            <template #tableCell="{ column, record }">
              <template v-if="column.key === 'protocolInfo'">
                <div style="line-height: 1.4;">
                  <div style="font-weight: 500; color: #262626; margin-bottom: 2px;">
                    {{ record.name }}
                  </div>
                  <div style="font-size: 12px; color: #8c8c8c;">
                    ID: {{ record.protocolId }}
                  </div>
                </div>
              </template>
              <template v-else-if="column.key === 'protocolType'">
                <a-tag :color="getProtocolTypeColor(record.protocolType)">
                  {{ getProtocolTypeName(record.protocolType) }}
                </a-tag>
              </template>
              <template v-else-if="column.key === 'channelCode'">
                <div v-if="record.channelCode" style="display: flex; align-items: center; gap: 8px;">
                  <template v-if="getChannelInfo(record.channelCode)">
                    <img 
                      :src="getChannelInfo(record.channelCode)?.iconUrl" 
                      :alt="getChannelInfo(record.channelCode)?.channelName" 
                      style="width: 20px; height: 20px; object-fit: contain;" 
                    />
                    <div>
                      <div style="font-weight: 500; font-size: 13px;">{{ getChannelInfo(record.channelCode)?.channelName }}</div>
                      <div style="font-size: 11px; color: #8c8c8c;">{{ record.channelCode }}</div>
                    </div>
                  </template>
                  <template v-else-if="record.channelCode === 'DEFAULT'">
                    <div style="width: 20px; height: 20px; display: flex; align-items: center; justify-content: center; background: #f0f0f0; border-radius: 4px;">
                      <span style="font-size: 12px; color: #999;">默</span>
                    </div>
                    <div>
                      <div style="font-weight: 500; font-size: 13px;">默认</div>
                      <div style="font-size: 11px; color: #8c8c8c;">{{ record.channelCode }}</div>
                    </div>
                  </template>
                  <template v-else>
                    <div style="width: 20px; height: 20px; display: flex; align-items: center; justify-content: center; background: #f0f0f0; border-radius: 4px;">
                      <span style="font-size: 12px; color: #999;">?</span>
                    </div>
                    <div>
                      <div style="font-weight: 500; font-size: 13px;">未知渠道</div>
                      <div style="font-size: 11px; color: #8c8c8c;">{{ record.channelCode }}</div>
                    </div>
                  </template>
                </div>
                <div v-else style="color: #bbb; font-size: 13px;">无</div>
              </template>
              <template v-else-if="column.key === 'configSections'">
                <a-tag
                  v-for="section in record.configSections.slice(0, 2)"
                  :key="section.sectionKey"
                  size="small"
                  style="margin-bottom: 4px"
                >
                  {{ section.sectionName }}
                </a-tag>
                <a-tag
                  v-if="record.configSections.length > 2"
                  size="small"
                  color="blue"
                >
                  +{{ record.configSections.length - 2 }}
                </a-tag>
              </template>
              <template v-else-if="column.key === 'action'">
                <div class="anypay-apple-actions">
                  <a-space>
                    <a-button type="link" @click="handleView(record)">
                      <EyeOutlined />查看
                    </a-button>
                    <a-button type="link" @click="handleViewDetails(record)">
                      <EyeOutlined />查看详情
                    </a-button>
                    <a-button type="link" @click="handleEdit(record)">
                      <EditOutlined />编辑
                    </a-button>
                    <a-button type="link" @click="handleTest(record)">
                      <ExperimentOutlined />测试
                    </a-button>
                    <a-dropdown placement="bottomRight">
                      <a-button type="link" size="small">
                        <MoreOutlined />
                        更多
                      </a-button>
                      <template #overlay>
                        <a-menu>
                          <a-menu-item key="copy" @click="handleCopy(record)">
                            <CopyOutlined />
                            复制协议
                          </a-menu-item>
                          <a-menu-item
                            key="export"
                            @click="handleExport(record)"
                          >
                            <DownloadOutlined />
                            导出配置
                          </a-menu-item>
                          <a-menu-divider />
                          <a-menu-item
                            key="toggle"
                            @click="handleToggleStatus(record)"
                          >
                            <CheckCircleOutlined />
                            {{ record.enabled ? "禁用" : "启用" }}
                          </a-menu-item>
                          <a-menu-item
                            key="delete"
                            @click="handleDelete(record)"
                            danger
                          >
                            <DeleteOutlined />
                            删除
                          </a-menu-item>
                        </a-menu>
                      </template>
                    </a-dropdown>
                  </a-space>
                </div>
              </template>
            </template>
          </AnyTable>
        </div>
      </a-card>
    </div>

    <!-- 新增/编辑协议对话框 -->
    <a-modal
      v-model:open="showEditDialog"
      :title="editDialogTitle"
      width="1200px"
      :footer="null"
      class="protocol-edit-modal"
    >
      <a-form
        ref="protocolFormRef"
        :model="protocolForm"
        :rules="protocolRules"
        layout="vertical"
      >
        <a-card class="edit-section" title="基本信息" :bordered="false">
          <a-row :gutter="16">
            <a-col :span="8">
              <a-form-item label="协议名称" name="name">
                <a-input
                  v-model:value="protocolForm.name"
                  placeholder="请输入协议名称"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="协议类型" name="protocolType">
                <a-select
                  v-model:value="protocolForm.protocolType"
                  placeholder="请选择协议类型"
                  @change="handleProtocolTypeChange"
                >
                  <a-select-option value="MERCHANT_CHANNEL_CONFIG_V3">商户渠道配置</a-select-option>
                  <a-select-option value="QR_CODE_CONFIG">二维码配置</a-select-option>
                  <a-select-option value="DEFAULT_PROTOCOL">默认协议</a-select-option>
                  <a-select-option value="CHANNEL_ONBOARDING">渠道进件协议</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="版本号" name="version">
                <a-input
                  v-model:value="protocolForm.version"
                  placeholder="请输入版本号"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="8">
              <a-form-item label="状态" name="enabled">
                <a-radio-group
                  v-model:value="protocolForm.enabled"
                  button-style="solid"
                >
                  <a-radio-button :value="true">启用</a-radio-button>
                  <a-radio-button :value="false">禁用</a-radio-button>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="渠道代码" name="channelCode">
                <a-input
                  v-model:value="protocolForm.channelCode"
                  placeholder="请输入渠道代码"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8" v-if="protocolForm.protocolType === 'QR_CODE_CONFIG'">
              <a-form-item label="二维码类型" name="codeType">
                <a-select
                  v-model:value="protocolForm.codeType"
                  placeholder="请选择二维码类型"
                >
                  <a-select-option value="STATIC">静态二维码</a-select-option>
                  <a-select-option value="DYNAMIC">动态二维码</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-form-item label="描述" name="description">
            <a-textarea
              v-model:value="protocolForm.description"
              placeholder="请输入协议描述"
              :rows="3"
            />
          </a-form-item>
        </a-card>

        <a-card class="edit-section" title="配置段管理" :bordered="false">
          <div class="config-sections-manager">
            <div class="sections-toolbar">
              <a-button type="dashed" @click="handleAddSection">
                <PlusOutlined /> 添加配置段
              </a-button>
            </div>

            <div class="sections-list">
              <a-card
                v-for="(section, index) in protocolForm.configSections"
                :key="section.sectionKey"
                size="small"
                class="section-card"
              >
                <template #title>
                  <a-input
                    v-model:value="section.sectionName"
                    placeholder="配置段标题"
                  />
                </template>
                <template #extra>
                  <a-space>
                    <a-button
                      type="link"
                      size="small"
                      @click="handleAddField(index)"
                    >
                      <PlusOutlined /> 添加字段
                    </a-button>
                    <a-button
                      type="link"
                      size="small"
                      danger
                      @click="handleRemoveSection(index)"
                    >
                      <DeleteOutlined /> 删除
                    </a-button>
                  </a-space>
                </template>

                <a-input
                  v-model:value="section.description"
                  placeholder="配置段描述"
                  style="margin-bottom: 16px"
                />

                <div class="fields-list">
                  <div
                    v-for="(field, fieldIndex) in section.fields"
                    :key="field.fieldKey"
                    class="field-item"
                  >
                    <a-row :gutter="8">
                      <a-col :span="4">
                        <a-input
                          v-model:value="field.fieldKey"
                          placeholder="字段ID"
                        />
                      </a-col>
                      <a-col :span="4">
                        <a-input
                          v-model:value="field.fieldName"
                          placeholder="字段标签"
                        />
                      </a-col>
                      <a-col :span="3">
                        <a-select
                          v-model:value="field.fieldType"
                          placeholder="类型"
                        >
                          <a-select-option value="INPUT">文本</a-select-option>
                          <a-select-option value="NUMBER">数字</a-select-option>
                          <a-select-option value="SWITCH">布尔</a-select-option>
                          <a-select-option value="SELECT">选择</a-select-option>
                          <a-select-option value="TEXTAREA">多行文本</a-select-option>
                          <a-select-option value="PASSWORD">密码</a-select-option>
                        </a-select>
                      </a-col>
                      <a-col :span="4">
                        <a-input
                          v-model:value="field.placeholder"
                          placeholder="占位符"
                        />
                      </a-col>
                      <a-col :span="4">
                        <a-input
                          v-model:value="field.defaultValue"
                          placeholder="默认值"
                        />
                      </a-col>
                      <a-col :span="2">
                        <a-checkbox v-model:checked="field.required">必填</a-checkbox>
                      </a-col>
                      <a-col :span="3">
                        <a-button
                          type="link"
                          size="small"
                          danger
                          @click="handleRemoveField(index, fieldIndex)"
                        >
                          <DeleteOutlined />
                        </a-button>
                      </a-col>
                    </a-row>
                  </div>
                </div>
              </a-card>
            </div>
          </div>
        </a-card>

        <div class="form-footer">
          <a-space>
            <a-button @click="handleCancelProtocol">取消</a-button>
            <a-button type="primary" @click="handleSaveProtocol">保存</a-button>
          </a-space>
        </div>
      </a-form>
    </a-modal>

    <!-- 查看协议对话框 -->
    <a-modal
      v-model:open="showViewDialog"
      title="查看协议详情"
      width="1000px"
      :footer="null"
      class="protocol-view-modal"
    >
      <a-descriptions bordered>
        <a-descriptions-item label="协议ID">
          {{ viewingProtocol.protocolId }}
        </a-descriptions-item>
        <a-descriptions-item label="协议名称">
          {{ viewingProtocol.name }}
        </a-descriptions-item>
        <a-descriptions-item label="版本">
          {{ viewingProtocol.version }}
        </a-descriptions-item>

        <a-descriptions-item label="协议类型">
          <a-tag :color="getProtocolTypeColor(viewingProtocol.protocolType)">
            {{ getProtocolTypeName(viewingProtocol.protocolType) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="状态">
          <a-tag :color="viewingProtocol.enabled ? 'green' : 'red'">
            {{ viewingProtocol.enabled ? "启用" : "禁用" }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="创建时间">
          {{ viewingProtocol.metadata?.createTime }}
        </a-descriptions-item>

        <a-descriptions-item label="描述" :span="3">
          {{ viewingProtocol.description }}
        </a-descriptions-item>

        <a-descriptions-item label="配置段数量">
          {{ viewingProtocol.configSections?.length || 0 }}
        </a-descriptions-item>
        <a-descriptions-item label="字段总数">
          {{ getTotalFieldsCount(viewingProtocol) }}
        </a-descriptions-item>
        <a-descriptions-item label="必填字段数">
          {{ getRequiredFieldsCount(viewingProtocol) }}
        </a-descriptions-item>
      </a-descriptions>


      <a-divider>配置段详情</a-divider>
      <a-collapse>
        <a-collapse-panel
          v-for="section in viewingProtocol.configSections"
          :key="section.sectionKey"
          :header="`${section.sectionName} (${section.fields?.length || 0} 个字段)`"
        >
          <a-table
            :dataSource="section.fields"
            :columns="fieldColumns"
            :pagination="false"
            size="small"
          />
        </a-collapse-panel>
      </a-collapse>
    </a-modal>

    <!-- 协议绑定管理对话框 -->
    <a-modal
      v-model:open="showBindingDialog"
      title="协议绑定管理"
      width="1200px"
      :footer="null"
      class="binding-management-modal"
    >
      <div class="binding-management">
        <div class="binding-toolbar">
          <a-space>
            <a-button type="primary" @click="handleCreateBinding">
              <PlusOutlined /> 创建绑定
            </a-button>
            <a-button @click="handleRefreshBindings">
              <ReloadOutlined /> 刷新
            </a-button>
          </a-space>
        </div>

        <a-table
          :dataSource="currentProtocolBindings"
          :columns="bindingManagementColumns"
          :pagination="false"
          size="small"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'status'">
              <a-tag :color="getBindingStatusColor(record.status)">
                {{ getBindingStatusName(record.status) }}
              </a-tag>
            </template>
            <template v-else-if="column.key === 'action'">
              <a-space>
                <a-button type="link" size="small" @click="handleEditBinding(record)">
                  <EditOutlined />编辑
                </a-button>
                <a-button type="link" size="small" @click="handleDeleteBinding(record)" danger>
                  <DeleteOutlined />删除
                </a-button>
              </a-space>
            </template>
          </template>
        </a-table>
      </div>
    </a-modal>

    <!-- 测试结果对话框 -->
    <a-modal
      v-model:open="showTestDialog"
      title="协议测试结果"
      width="800px"
      :footer="null"
    >
      <div v-if="testResult">
        <a-result
          :status="testResult.success ? 'success' : 'error'"
          :title="testResult.success ? '测试通过' : '测试失败'"
          :sub-title="`耗时: ${testResult.duration}ms`"
        >
          <template #extra>
            <a-space>
              <a-button @click="showTestDialog = false">关闭</a-button>
              <a-button
                type="primary"
                @click="handleRetestCurrent"
                v-if="!testResult.success"
              >
                重新测试
              </a-button>
            </a-space>
          </template>
        </a-result>

        <a-divider v-if="testResult.errors?.length > 0">错误信息</a-divider>
        <a-alert
          v-for="(error, index) in testResult.errors || []"
          :key="index"
          :message="error"
          type="error"
          style="margin-bottom: 8px"
        />

        <a-divider v-if="testResult.warnings?.length > 0">警告信息</a-divider>
        <a-alert
          v-for="(warning, index) in testResult.warnings || []"
          :key="index"
          :message="warning"
          type="warning"
          style="margin-bottom: 8px"
        />
      </div>
    </a-modal>

    <!-- Protocol3 协议信息抽屉 -->
    <ProtocolInfoDrawer
      v-model:visible="showProtocolDrawer"
      :protocol="currentProtocol"
      :is-default="false"
      @close="handleCloseProtocolDrawer"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { message } from "ant-design-vue";
import {
  PlusOutlined,
  EditOutlined,
  EyeOutlined,
  SearchOutlined,
  ReloadOutlined,
  MoreOutlined,
  DeleteOutlined,
  ExperimentOutlined,
  CheckCircleOutlined,
  CopyOutlined,
  DownloadOutlined,
  LinkOutlined,
} from "@ant-design/icons-vue";
import { protocol3Manager } from "@/mock/protocol3-manager";
import { protocol3Resolver } from "@/mock/protocol3-resolver";
import { protocol3Tester } from "@/mock/protocol3-tester";
import { initializeSampleData } from "@/mock/protocol3-sample-data";
import { paymentChannels } from "@/mock/channels";
import {
  ProtocolType3,
  ProtocolBindingStatus,
  type MerchantChannelConfig3,
  type QRCodeConfig,
  type DefaultProtocol,
  type ProtocolBinding,
  type ConfigSection,
  type ConfigField,
  type TestResult,
} from "@/types/protocol3-types";
import AnyTable from "@/components/AnyTable.vue";
import ProtocolInfoDrawer from "@/components/ProtocolInfoDrawer.vue";
import type { AnyProtocol } from "@/types/channel-config-protocol";

// 响应式数据
const showEditDialog = ref(false);
const showViewDialog = ref(false);
const showTestDialog = ref(false);
const showBindingDialog = ref(false);
const showProtocolDrawer = ref(false);
const currentProtocol = ref<AnyProtocol | null>(null);

// 组件引用
const protocolTable = ref();
const protocolFormRef = ref();

// 表单数据
const searchForm = reactive({
  protocolType: undefined,
  enabled: undefined,
  channelCode: undefined,
});

// 搜索参数
const searchParams = reactive<{
  protocolType?: string;
  enabled?: boolean;
  channelCode?: string;
}>({});

const protocolForm = reactive<MerchantChannelConfig3 | QRCodeConfig>({
  protocolId: "",
  protocolType: ProtocolType3.MERCHANT_CHANNEL_CONFIG_V3,
  channelCode: "",
  name: "",
  version: "3.0.0",
  description: "",
  enabled: true,
  configSections: [],
  uiConfig: {
    layout: "horizontal",
    labelWidth: 120,
    showDescription: true,
    grouping: "sections",
  },
  metadata: {
    author: "AnyPay Team",
    createTime: new Date().toISOString(),
    updateTime: new Date().toISOString(),
    tags: [],
    category: "自定义协议",
  },
});

const viewingProtocol = reactive<MerchantChannelConfig3 | QRCodeConfig>({} as any);
const testResult = ref<TestResult | null>(null);
const currentTestProtocolId = ref("");
const currentProtocolBindings = ref<ProtocolBinding[]>([]);

// 编辑对话框标题
const editDialogTitle = computed(() => {
  return protocolForm.protocolId ? "编辑协议" : "新增协议";
});

// 表格列定义
const tableColumns = [
  {
    title: "协议信息",
    key: "protocolInfo",
    width: 250,
  },
  {
    title: "协议类型",
    key: "protocolType",
    width: 150,
    align: "center",
  },
  {
    title: "渠道",
    key: "channelCode",
    width: 180,
  },
  {
    title: "配置段",
    key: "configSections",
    width: 200,
  },
  {
    title: "操作",
    key: "action",
    width: 280,
    align: "center",
  },
];

// 字段表格列定义
const fieldColumns = [
  { title: "字段ID", dataIndex: "fieldKey", key: "fieldKey" },
  { title: "标签", dataIndex: "fieldName", key: "fieldName" },
  { title: "类型", dataIndex: "fieldType", key: "fieldType" },
  { title: "必填", dataIndex: "required", key: "required" },
  { title: "默认值", dataIndex: "defaultValue", key: "defaultValue" },
];

// 绑定表格列定义
const bindingColumns = [
  { title: "渠道", dataIndex: "channelCode", key: "channelCode" },
  { title: "配置类型", dataIndex: "configType", key: "configType" },
  { title: "状态", dataIndex: "status", key: "status" },
  { title: "优先级", dataIndex: "priority", key: "priority" },
  { title: "创建时间", dataIndex: "createTime", key: "createTime" },
];

// 绑定管理表格列定义
const bindingManagementColumns = [
  { title: "绑定ID", dataIndex: "bindingId", key: "bindingId", width: 200 },
  { title: "渠道", dataIndex: "channelCode", key: "channelCode" },
  { title: "配置类型", dataIndex: "configType", key: "configType" },
  { title: "状态", key: "status", width: 100 },
  { title: "优先级", dataIndex: "priority", key: "priority" },
  { title: "描述", dataIndex: "description", key: "description" },
  { title: "操作", key: "action", width: 120 },
];

// 表单验证规则
const protocolRules = {
  name: [{ required: true, message: "请输入协议名称", trigger: "blur" }],
  protocolType: [{ required: true, message: "请选择协议类型", trigger: "change" }],
  version: [{ required: true, message: "请输入版本号", trigger: "blur" }],
  channelCode: [
    { pattern: /^[A-Z_][A-Z0-9_]*$/, message: "渠道代码只能包含大写字母、数字和下划线，且必须以字母或下划线开头", trigger: "blur" }
  ],
};

// 组件挂载时初始化数据
onMounted(async () => {
  await initializeSampleData();
});

// 数据加载函数
const loadProtocolData = async (params: any) => {
  try {
    await new Promise((resolve) => setTimeout(resolve, 500));

    let filteredData = protocol3Manager.getAllProtocols();

    // 应用搜索筛选
    if (params.protocolType) {
      filteredData = filteredData.filter(
        (item) => item.protocolType === params.protocolType
      );
    }

    if (params.enabled !== undefined) {
      filteredData = filteredData.filter(
        (item) => item.enabled === params.enabled
      );
    }

    if (params.channelCode !== undefined) {
      if (params.channelCode === "") {
        // 搜索无渠道的协议
        filteredData = filteredData.filter(
          (item) => !item.channelCode || item.channelCode === ""
        );
      } else {
        // 搜索指定渠道的协议
        filteredData = filteredData.filter(
          (item) => item.channelCode === params.channelCode
        );
      }
    }

    // 排序：先按协议类型排序，然后按渠道排序
    filteredData.sort((a, b) => {
      // 协议类型排序权重
      const protocolTypeOrder = {
        'MERCHANT_CHANNEL_CONFIG_V3': 1,
        'QR_CODE_CONFIG': 2,
        'CHANNEL_ONBOARDING': 3,
        'DEFAULT_PROTOCOL': 4
      };
      
      const aTypeOrder = protocolTypeOrder[a.protocolType as keyof typeof protocolTypeOrder] || 999;
      const bTypeOrder = protocolTypeOrder[b.protocolType as keyof typeof protocolTypeOrder] || 999;
      
      if (aTypeOrder !== bTypeOrder) {
        return aTypeOrder - bTypeOrder;
      }
      
      // 协议类型相同时，按渠道排序
      const aChannel = a.channelCode || '';
      const bChannel = b.channelCode || '';
      return aChannel.localeCompare(bChannel);
    });

    // 计算分页
    const startIndex = ((params.pageNumber || 1) - 1) * (params.pageSize || 10);
    const endIndex = startIndex + (params.pageSize || 10);
    const records = filteredData.slice(startIndex, endIndex);

    return {
      records,
      total: filteredData.length,
      pageNumber: params.pageNumber || 1,
      pageSize: params.pageSize || 10,
    };
  } catch (error) {
    console.error("Failed to load protocol data:", error);
    return { records: [], total: 0, pageNumber: 1, pageSize: 10 };
  }
};

// 方法
const handleCreate = () => {
  resetProtocolForm();
  showEditDialog.value = true;
};

const handleEdit = (record: MerchantChannelConfig3 | QRCodeConfig | DefaultProtocol) => {
  Object.assign(protocolForm, record);
  showEditDialog.value = true;
};

const handleView = (record: MerchantChannelConfig3 | QRCodeConfig | DefaultProtocol) => {
  Object.assign(viewingProtocol, record);
  showViewDialog.value = true;
};

const handleViewDetails = (record: MerchantChannelConfig3 | QRCodeConfig | DefaultProtocol) => {
  // 将 Protocol3 格式转换为 AnyProtocol 格式
  const convertedProtocol = convertToAnyProtocol(record);
  currentProtocol.value = convertedProtocol;
  showProtocolDrawer.value = true;
};

const handleCloseProtocolDrawer = () => {
  showProtocolDrawer.value = false;
  currentProtocol.value = null;
};

const handleManageBindings = () => {
  showBindingDialog.value = true;
  handleRefreshBindings();
};

const handleManageProtocolBindings = (record: MerchantChannelConfig3 | QRCodeConfig | DefaultProtocol) => {
  currentProtocolBindings.value = protocol3Manager.getProtocolBindings(record.protocolId);
  showBindingDialog.value = true;
};

const handleCreateBinding = () => {
  message.info("创建绑定功能待实现");
};

const handleEditBinding = (binding: ProtocolBinding) => {
  message.info("编辑绑定功能待实现");
};

const handleDeleteBinding = (binding: ProtocolBinding) => {
  protocol3Manager.deleteProtocolBinding(binding.bindingId);
  message.success("删除绑定成功");
  handleRefreshBindings();
};

const handleRefreshBindings = () => {
  currentProtocolBindings.value = protocol3Manager.getAllProtocolBindings();
};

const handleTest = async (record: MerchantChannelConfig3 | QRCodeConfig | DefaultProtocol) => {
  currentTestProtocolId.value = record.protocolId;
  testResult.value = protocol3Tester.testProtocol(record.protocolId);
  showTestDialog.value = true;
};

const handleTestAll = async () => {
  const results = protocol3Tester.testAllProtocols();
  const successCount = results.passedTests;
  const totalCount = results.totalTests;
  message.info(`批量测试完成: ${successCount}/${totalCount} 个协议通过测试`);
};

const handleClearCache = () => {
  protocol3Manager.clearCache();
  protocol3Resolver.clearCache();
  message.success("缓存清理成功");
};

const handleTestProtocolLookup = () => {
  // 测试协议查找功能
  const testCases = [
    { protocolCode: 'CHANNEL_PROTOCOL_WECHAT', configType: 'PROVIDER' },
    { protocolCode: 'CHANNEL_PROTOCOL_WECHAT', configType: 'DIRECT_MERCHANT' },
    { protocolCode: 'CHANNEL_PROTOCOL_ALIPAY', configType: 'PROVIDER' },
    { protocolCode: 'CHANNEL_PROTOCOL_UNKNOWN', configType: 'PROVIDER' }, // 测试兜底协议
  ];
  
  console.log('\n=== 协议查找测试 ===');
  testCases.forEach(({ protocolCode, configType }) => {
    const result = protocol3Manager.getProtocolByConvention(protocolCode, configType);
    console.log(`${protocolCode} + ${configType} -> ${result}`);
  });
  
  message.success('协议查找测试完成，请查看控制台输出');
};

const handleCopy = (record: MerchantChannelConfig3 | QRCodeConfig | DefaultProtocol) => {
  const copied = { ...record };
  copied.protocolId = `${record.protocolId}_COPY_${Date.now()}`;
  copied.name = `${record.name} (副本)`;
  
  if (record.protocolType === ProtocolType3.MERCHANT_CHANNEL_CONFIG_V3) {
    protocol3Manager.registerMerchantChannelConfig(copied as MerchantChannelConfig3);
  } else if (record.protocolType === ProtocolType3.QR_CODE_CONFIG) {
    protocol3Manager.registerQRCodeConfig(copied as QRCodeConfig);
  } else if (record.protocolType === ProtocolType3.DEFAULT_PROTOCOL) {
    protocol3Manager.registerDefaultProtocol(copied as DefaultProtocol);
  }
  
  message.success("协议复制成功");
  searchProtocols();
};

const handleExport = (record: MerchantChannelConfig3 | QRCodeConfig | DefaultProtocol) => {
  const dataStr = JSON.stringify(record, null, 2);
  const blob = new Blob([dataStr], { type: "application/json" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = `${record.protocolId}.json`;
  a.click();
  URL.revokeObjectURL(url);
  message.success("协议导出成功");
};

const handleDelete = (record: MerchantChannelConfig3 | QRCodeConfig | DefaultProtocol) => {
  protocol3Manager.unregisterProtocol(record.protocolId);
  message.success(`删除协议 ${record.name} 成功`);
  searchProtocols();
};

const handleToggleStatus = (record: MerchantChannelConfig3 | QRCodeConfig | DefaultProtocol) => {
  record.enabled = !record.enabled;
  
  if (record.protocolType === ProtocolType3.MERCHANT_CHANNEL_CONFIG_V3) {
    protocol3Manager.registerMerchantChannelConfig(record as MerchantChannelConfig3);
  } else if (record.protocolType === ProtocolType3.QR_CODE_CONFIG) {
    protocol3Manager.registerQRCodeConfig(record as QRCodeConfig);
  } else if (record.protocolType === ProtocolType3.DEFAULT_PROTOCOL) {
    protocol3Manager.registerDefaultProtocol(record as DefaultProtocol);
  }
  
  const action = record.enabled ? "启用" : "禁用";
  message.success(`${action}协议成功`);
};

const handleSearch = () => {
  Object.keys(searchParams).forEach((key) => {
    delete (searchParams as any)[key];
  });

  if (searchForm.protocolType) {
    searchParams.protocolType = searchForm.protocolType;
  }
  if (searchForm.enabled !== undefined) {
    searchParams.enabled = searchForm.enabled;
  }
  if (searchForm.channelCode !== undefined) {
    searchParams.channelCode = searchForm.channelCode;
  }

  searchProtocols();
};

const handleReset = () => {
  Object.assign(searchForm, {
    protocolType: undefined,
    enabled: undefined,
    channelCode: undefined,
  });

  Object.keys(searchParams).forEach((key) => {
    delete (searchParams as any)[key];
  });

  searchProtocols();
};

const searchProtocols = () => {
  protocolTable.value?.refreshTable(true);
};

const handleSaveProtocol = async () => {
  try {
    await protocolFormRef.value?.validate();

    if (!protocolForm.protocolId) {
      protocolForm.protocolId = `PROTOCOL3_${Date.now()}`;
    }

    protocolForm.metadata.updateTime = new Date().toISOString();
    
    if (protocolForm.protocolType === ProtocolType3.MERCHANT_CHANNEL_CONFIG_V3) {
      protocol3Manager.registerMerchantChannelConfig(protocolForm as MerchantChannelConfig3);
    } else if (protocolForm.protocolType === ProtocolType3.QR_CODE_CONFIG) {
      protocol3Manager.registerQRCodeConfig(protocolForm as QRCodeConfig);
    } else if (protocolForm.protocolType === ProtocolType3.DEFAULT_PROTOCOL) {
      protocol3Manager.registerDefaultProtocol(protocolForm as DefaultProtocol);
    }

    message.success(protocolForm.protocolId ? "编辑协议成功" : "新增协议成功");
    showEditDialog.value = false;
    searchProtocols();
  } catch (error) {
    message.error("保存失败");
  }
};

const handleCancelProtocol = () => {
  showEditDialog.value = false;
  resetProtocolForm();
};

const handleProtocolTypeChange = (value: string) => {
  if (value === ProtocolType3.QR_CODE_CONFIG) {
    (protocolForm as QRCodeConfig).codeType = 'STATIC';
  }
};

const handleAddSection = () => {
  const newSection: ConfigSection = {
    sectionKey: `section_${Date.now()}`,
    sectionName: "新配置段",
    description: "",
    icon: "SettingOutlined",
    order: protocolForm.configSections.length + 1,
    collapsed: false,
    fields: [],
    defaultValues: {},
  };
  protocolForm.configSections.push(newSection);
};

const handleRemoveSection = (index: number) => {
  protocolForm.configSections.splice(index, 1);
};

const handleAddField = (sectionIndex: number) => {
  const newField: ConfigField = {
    fieldKey: `field_${Date.now()}`,
    fieldName: "新字段",
    fieldType: "INPUT" as any,
    required: false,
    placeholder: "",
    defaultValue: "",
  };
  protocolForm.configSections[sectionIndex].fields.push(newField);
};

const handleRemoveField = (sectionIndex: number, fieldIndex: number) => {
  protocolForm.configSections[sectionIndex].fields.splice(fieldIndex, 1);
};

const handleRetestCurrent = () => {
  if (currentTestProtocolId.value) {
    testResult.value = protocol3Tester.testProtocol(currentTestProtocolId.value);
  }
};

const resetProtocolForm = () => {
  Object.assign(protocolForm, {
    protocolId: "",
    protocolType: ProtocolType3.MERCHANT_CHANNEL_CONFIG_V3,
    channelCode: "",
    name: "",
    version: "3.0.0",
    description: "",
    enabled: true,
    configSections: [],
    uiConfig: {
      layout: "horizontal",
      labelWidth: 120,
      showDescription: true,
      grouping: "sections",
    },
    metadata: {
      author: "AnyPay Team",
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString(),
      tags: [],
      category: "自定义协议",
    },
  });
};

const handleLoadComplete = () => {
  console.log("Protocol3 data loaded successfully");
};

// 辅助函数
const getProtocolTypeName = (type: string) => {
  const names = {
    MERCHANT_CHANNEL_CONFIG_V3: "商户渠道配置",
    QR_CODE_CONFIG: "二维码配置",
    DEFAULT_PROTOCOL: "默认协议",
    CHANNEL_ONBOARDING: "渠道进件协议",
  };
  return names[type as keyof typeof names] || type;
};

const getProtocolTypeColor = (type: string) => {
  const colors = {
    MERCHANT_CHANNEL_CONFIG_V3: "blue",
    QR_CODE_CONFIG: "green",
    DEFAULT_PROTOCOL: "orange",
    CHANNEL_ONBOARDING: "purple",
  };
  return colors[type as keyof typeof colors] || "default";
};

// 获取渠道信息
const getChannelInfo = (channelCode: string) => {
  return paymentChannels.find(channel => channel.channelCode === channelCode);
};

// 数据转换函数：将 Protocol3 格式转换为 AnyProtocol 格式
const convertToAnyProtocol = (protocol3: MerchantChannelConfig3 | QRCodeConfig | DefaultProtocol): AnyProtocol => {
  // 根据协议类型确定映射
  const protocolType = protocol3.protocolType as any;
  
  // 转换配置段格式
  const convertedConfigSections = protocol3.configSections?.map(section => ({
    ...section,
    fields: section.fields?.map(field => ({
      ...field,
      fieldType: field.fieldType as any, // 类型转换
      validation: field.validation || {},
      defaultValue: field.defaultValue || ''
    })) || []
  })) || [];

  // 获取渠道信息
  const channelInfo = protocol3.channelCode ? getChannelInfo(protocol3.channelCode) : null;

  // 构造 AnyProtocol 对象
  const anyProtocol: AnyProtocol = {
    protocolId: protocol3.protocolId,
    protocolType: protocolType,
    name: protocol3.name,
    version: protocol3.version,
    description: protocol3.description,
    configFields: convertedConfigSections,
    defaultValues: protocol3.defaultValues || {},
    uiConfig: protocol3.uiConfig || {},
    metadata: protocol3.metadata || {},
    enabled: protocol3.enabled,
    configSections: convertedConfigSections,
    // 添加渠道信息
    channelCode: protocol3.channelCode,
    channelName: channelInfo?.channelName || protocol3.channelCode
  };

  return anyProtocol;
};

const getProtocolBindings = (protocolId: string): ProtocolBinding[] => {
  return protocol3Manager.getProtocolBindings(protocolId);
};

const getBindingStatusName = (status: string) => {
  const names = {
    ACTIVE: "激活",
    INACTIVE: "停用",
    PENDING: "待激活",
  };
  return names[status as keyof typeof names] || status;
};

const getBindingStatusColor = (status: string) => {
  const colors = {
    ACTIVE: "green",
    INACTIVE: "red",
    PENDING: "orange",
  };
  return colors[status as keyof typeof colors] || "default";
};

const getTotalFieldsCount = (protocol: MerchantChannelConfig3 | QRCodeConfig) => {
  return (
    protocol.configSections?.reduce(
      (total, section) => total + (section.fields?.length || 0),
      0
    ) || 0
  );
};

const getRequiredFieldsCount = (protocol: MerchantChannelConfig3 | QRCodeConfig) => {
  return (
    protocol.configSections?.reduce(
      (total, section) =>
        total + (section.fields?.filter((field) => field.required).length || 0),
      0
    ) || 0
  );
};
</script>

<style scoped>
@import "../common/list-page.css";

.protocol-edit-modal {
  :deep(.ant-modal-body) {
    padding: 0;
  }
}

.edit-section {
  margin-bottom: 16px;

  :deep(.ant-card-head) {
    padding: 8px 16px;
    min-height: 40px;
    background: #fafafa;
    border-bottom: 1px solid #f0f0f0;
  }

  :deep(.ant-card-body) {
    padding: 16px;
  }
}

.form-footer {
  padding: 16px;
  text-align: right;
  background: #fff;
  border-top: 1px solid #f0f0f0;
}

.config-sections-manager {
  .sections-toolbar {
    margin-bottom: 16px;
  }

  .section-card {
    margin-bottom: 16px;
  }

  .field-item {
    margin-bottom: 8px;
    padding: 8px;
    background: #fafafa;
    border-radius: 4px;
  }
}

.protocol-view-modal {
  :deep(.ant-descriptions-item-label) {
    width: 120px;
    background-color: #fafafa;
  }
}

.binding-management-modal {
  .binding-management {
    .binding-toolbar {
      margin-bottom: 16px;
    }
  }
}
</style>